package com.flc.gateway.cmdqueue;

import com.flc.gateway.config.AppConfig;
import com.flc.gateway.dataqueue.LoginQueue;
import com.flc.gateway.model.CommandHelper;
import com.flc.gateway.session.SessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @author haizi
 * @date 2018/1/2
 */
public class CmdQueue extends Thread {

    private static final Logger logger = LoggerFactory.getLogger(LoginQueue.class);

    public CmdQueue(int capacity, AppConfig.RocketMqCfg rocketMqCfg) {
        super.setName("CmdQueue");
        this.dataQueue = new ArrayBlockingQueue<>(capacity);
    }

    @Override
    public void run() {
        logger.info("开启下发指令队列...");
        while (true) {
            try {
                CommandHelper cmd = this.take();
                // ToDo 把取到的数据发往登陆对应的设备
                if (SessionManager.sendCmdToDevice(cmd)) {
                    logger.info("准备下发数据了要。。。");
                } else {
                    logger.info("无法下发，该设备不在线！");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void put(CommandHelper data) {
        try {
            dataQueue.put(data);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private CommandHelper take() throws InterruptedException {
        return dataQueue.take();
    }

    private BlockingQueue<CommandHelper> dataQueue;

}
